<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    /**
     * 用户注册
     */
    public function register(Request $request)
    {
        $validated = $request->validate([
            'phone' => 'required|unique:users',
            'password' => 'required|min:6',
            'username' => 'required|string|max:255',
            'avatar' => 'nullable|string',
            'bio' => 'nullable|string',
        ]);

        $user = User::create([
            'phone' => $validated['phone'],
            'password' => Hash::make($validated['password']),
            'username' => $validated['username'],
            'avatar' => $validated['avatar'] ?? null,
            'bio' => $validated['bio'] ?? null,
        ]);

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'user' => $user,
            'token' => $token
        ], 201);
    }

    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        $validated = $request->validate([
            'phone' => 'required',
            'password' => 'required',
        ]);

        if (Auth::attempt($validated)) {
            $user = Auth::user();
            $token = $user->createToken('auth_token')->plainTextToken;
            return response()->json([
                'user' => $user,
                'token' => $token
            ], 200);
        }

        return response()->json(['message' => '手机号或密码错误'], 401);
    }

    /**
     * 获取用户信息
     */
    public function user(Request $request)
    {
        return response()->json($request->user());
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => '退出登录成功'], 200);
    }
}